package com.sun.common.authoriza;

import com.github.yulichang.query.MPJQueryWrapper;
import com.sun.common.authoriza.provider.CurrentUser;
import com.sun.common.model.GroupModel;
import com.sun.common.model.UserModel;
import com.sun.common.service.GroupService;
import com.sun.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AuthService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

    /**
     * 根据用户名查询用户详细信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserModel user=userService.lambdaQuery().eq(UserModel::getAccount,username).one();
        if (user == null) {
            throw new UsernameNotFoundException(String.format("找不到此用户名%s。", username));
        }
        MPJQueryWrapper<GroupModel> wrapperM=new MPJQueryWrapper<GroupModel>()
                .select("t.name AS roleCode ")
                .innerJoin(" zt_usergroup ug ON t.id = ug.group");
        wrapperM.eq("ug.account",user.getAccount());
        List<Map<String, Object>> lm=groupService.selectJoinMaps(wrapperM);
        List<String> roleCodeList=new ArrayList<>();
        lm.forEach(m->roleCodeList.add(m.get("roleCode")+""));
        return new CurrentUser(username, user.getPassword(), AuthorityUtils.createAuthorityList(roleCodeList.toArray(new String[]{})),user);
    }
}
